<?php

namespace app\bot\admin;

use app\common\builder\ZBuilder;
use app\bot\model\Operatelog as OperatelogModel;
use app\bot\model\Download as DownloadModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 操作日志控制器
 */
class Operatelog extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if ($this->no_auth) {
            $this->error('权限不足！');
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {
                if ($map_v1[0] == 'remark') {
                    $map[$map_k1][1] = 'like';
                    $map[$map_k1][2] = '%' . $map[$map_k1][2] . '%';
                }
            }
        }

        // 数据列表
        $data_list = OperatelogModel::where($map)->order('id desc')->paginate();

        // 分页数据
        $page = $data_list->render();

        $date = date('Y-m-d');
        $search = [
            ['daterange:3', 'create_time', '时间查询', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:2', 'status', '状态', '', '', ['一般', '重要']],
            ['text:2', 'uid', '用户id'],
            ['text:2', 'remark', '日志备注'],
        ];

        $items = [
            ['id', 'ID'],
            ['uid', '用户id'],
            ['url', 'url'],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status', '', ['一般', '重要']],
            ['right_button', '操作', 'btn']
        ];

        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('操作日志') // 设置页面标题
            ->setTableName('bot_operate_log') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->addColumns($items)
            ->addTopButtons('delete') // 批量添加顶部按钮
            // ->addTopButton('export', $export) // 添加按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], false)
            ->addRightButtons('delete') // 批量添加右侧按钮
            ->setSearchArea($search) // 设置搜索区域  
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }


    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        $count = OperatelogModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }

        // 最多导出数量
        $export_order_max_count = bot_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = bot_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "重要错误日志导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败");
        }

        $field = [
            'id',
            'code',
            'title',
            'remark',
            'status',
            'create_time',
        ];
        if ($this->no_auth) {
        }
        $cellName = [
            'id',
            '错误编码',
            '标题',
            '日志备注',
            '状态',
            '创建时间',
        ];
        if ($this->no_auth) {
        }

        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('bot_log')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp) {
                foreach ($all as $single) {

                    $single['status'] = $single['status'] ? '重要' : '一般';
                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['remark'] = format_nice($single['remark']);

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'id', 'asc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }
        // 获取数据
        $info = OperatelogModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        $info['remark'] = format_nice($info['remark']);
        $items = [
            ['static', 'id', '主键'],
            ['static', 'uid', '用户id', '', '', '', ''],
            ['static', 'url', 'url', '', '', '', ''],
            ['textarea', 'remark', '日志备注', '', '', '', ''],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['radio', 'status', '状态', '', ['一般', '重要'], '', '', 'disabled', ''],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->setPageTips("说明：重要日志。")
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = OperatelogModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['bot_operate_log_' . $type, 'bot_operate_log', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = OperatelogModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['bot_operate_log_edit', 'bot_operate_log', $id, UID, $details]);
    }
}
